﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Rj_GsInsurance.Server.Extensions
{
    public class KernelExtensions
    {
        private static class KernelHelper
        {
            [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
            public static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
            [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
            public static extern IntPtr GetProcAddress(int hModule, [MarshalAs(UnmanagedType.LPStr)] string lpProcName);
            [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
            public static extern bool FreeLibrary(int hModule);
        }



        public static TDelegate CreateDelInstance<TDelegate>(string dllPath, string methodName)
        {
            int hModule = KernelHelper.LoadLibrary(dllPath);
            if (hModule == 0)
            {
                return default(TDelegate);
            }
            IntPtr intPtr = KernelHelper.GetProcAddress(hModule, methodName);
            return Marshal.GetDelegateForFunctionPointer<TDelegate>(intPtr);
        }

    }
}
